//
//  CXEmotionBar.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/28.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

class CXEmotionBar: UIStackView {

    /// 遵守了协议的代理
    weak var delegate: CXEmotionBarDelegate?
    /// 记录当前处于选中状态的按钮；（为了能够体现被点击按钮的被选中的效果）
    var currentSelButton: UIButton?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
///  @objc与optional可以搭配创建可选方法
protocol CXEmotionBarDelegate: NSObjectProtocol {
    func emotionBarButtonDidClick(button: UIButton, type: CXEmoticonType)
}
// MARK: - 设置UI
extension CXEmotionBar {
    
    private func setupUI() {
        
        distribution = .FillEqually
        
        addButton("最近", imageName: "compose_emotion_table_left", type: .Recent)
        addButton("默认", imageName: "compose_emotion_table_mid", type: .Default)
        addButton("Emoji", imageName: "compose_emotion_table_mid", type: .Emoji)
        addButton("浪小花", imageName: "compose_emotion_table_right", type: .Lxh)
    }
    
    private func addButton(title: String, imageName: String, type: CXEmoticonType) {
        
        let button = UIButton()
        
        button.tag = type.rawValue + 1000 //tag等于0的时候 找不到button 因此要加上一个任意数值避开
        button.setBackgroundImage(UIImage(named: "\(imageName)_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "\(imageName)_selected"), forState: .Selected)
        
        button.setTitle(title, forState: .Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Selected)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.addTarget(self, action: "buttonDidClick:", forControlEvents: .TouchUpInside)
        
        addArrangedSubview(button)
    }
}
// MARK: - 各种事件
extension CXEmotionBar {
    ///  按钮点击 表情栏滚动
    @objc private func buttonDidClick(button: UIButton) {
        
        if currentSelButton == button {
            return
        }
        //点哪个就亮哪个
        currentSelButton?.selected = false
        button.selected = true
        currentSelButton = button
        
        delegate?.emotionBarButtonDidClick(button, type: CXEmoticonType(rawValue: button.tag - 1000)!)
    }
    
    //配合collectionView的滚动而切换按钮的选中状态. 传入的参数是对应表情类型的原始值
    func buttonSelect(section: Int) {
        
        let button = viewWithTag(section + 1000) as! UIButton
        //在这里也要判断即将选中的按钮是否就是当前按钮
        if button == currentSelButton {
            return
        }
        currentSelButton?.selected = false
        button.selected = true
        currentSelButton = button
    }
}
// MARK: - 表情种类
enum CXEmoticonType: Int {
    case Recent = 0
    case Default = 1
    case Emoji = 2
    case Lxh = 3
}